package controller

import (
	"fmt"
	"strings"
	"time"
	"uap/common"
	"uap/pkg/app"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

type TbApp struct {
	Id         int64  `gorm:"column:id;primary_key;NOT NULL" json:"id"` //id
	AppId      string `gorm:"column:app_id" json:"appId"`               //应用ID
	AppImg     string `gorm:"column:app_img" json:"appImg"`             //应用图标
	AppName    string `gorm:"column:app_name" json:"appName"`           //应用名称
	AppSecret  string `gorm:"column:app_secret" json:"appSecret"`       //应用密钥
	CreateDate string `gorm:"column:create_date" json:"createDate"`     //创建时间
}

func NewTbApp() *TbApp {
	return &TbApp{}
}

func (a *TbApp) List(c *gin.Context) {
	var list []TbApp
	common.Db.Table("tb_app").Scan(&list)
	app.Success(c, list)
}

func (a *TbApp) Add(c *gin.Context) {
	var tbapp TbApp
	err := c.ShouldBind(&tbapp)
	if err != nil {
		fmt.Println(err)
	}
	tbapp.CreateDate = time.Now().Format("2006-01-02 15:04:05")
	appId := strings.ReplaceAll(uuid.NewString(), "-", "")
	tbapp.AppId = appId
	appSecret := strings.ReplaceAll(uuid.NewString(), "-", "")
	tbapp.AppSecret = appSecret
	common.Db.Table("tb_app").Create(&tbapp)
	app.Success(c, "")
}

func (a *TbApp) Delete(c *gin.Context) {
	id := c.DefaultQuery("id", "")
	var tbApp TbApp
	common.Db.Debug().Table("tb_app").Where("id=?", id).Delete(&tbApp)
	app.Success(c, "")
}

func (a *TbApp) Update(c *gin.Context) {
	var tbapp TbApp
	err := c.ShouldBind(&tbapp)
	if err != nil {
		fmt.Println(err)
	}
	common.Db.Table("tb_app").Updates(tbapp)
	app.Success(c, "")
}

func (a *TbApp) GetById(c *gin.Context) {
	id := c.DefaultQuery("id", "")
	var tbApp TbApp
	common.Db.Table("tb_app").Where("id = ?", id).First(&tbApp)
	app.Success(c, tbApp)
}

func (a *TbApp) GetByAppId(c *gin.Context) {
	appId := c.DefaultQuery("appId", "")
	var tbApp TbApp
	common.Db.Table("tb_app").Where("app_id = ?", appId).First(&tbApp)
	app.Success(c, tbApp)
}
